﻿using Grow.Module;
using Grow.Module.AspNetCore;
using Grow.Module.AspNetCore.Service;
using Grow.Module.Service;
using Grow.WebAPI.CreateWebAPI;
using Grow.WebAPI.MiniAPI.CreateWebAPI;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

namespace Grow.WebAPI.MiniAPI
{
    public abstract class MiniAPIModuleBase : AspNetCoreModuleBase, IWebAPIModule
    {
        public override ModuleLevel Level => ModuleLevel.Framework;

        public override void AddDependModule(IDependModuleBuilder dependModuleBuilder)
        {
        }


        public override void AddService(IServiceContainer serviceContainer)
        {

            CreateWebAPIBuilder createWebAPIBuilder = new();
            CreateWebAPI(createWebAPIBuilder);
            serviceContainer.BuilderManager.SetBuilder<ICreateWebAPIBuilder>(createWebAPIBuilder);

            IEnumerable<IWebAPIMap> webAPIMaps = createWebAPIBuilder.GetWebAPIMaps();
            //Swagger
            _ = serviceContainer.ServiceCollection.AddEndpointsApiExplorer();
            _ = serviceContainer.ServiceCollection.AddSwaggerGen(a =>
            {

                foreach (IWebAPIMap webAPIMap in webAPIMaps)
                {
                    a.SwaggerDoc(webAPIMap.Group, new OpenApiInfo { Title = webAPIMap.Title, Version = webAPIMap.Group, Description = webAPIMap.Description });
                }
            });
        }

        public abstract void CreateWebAPI(ICreateWebAPIBuilder createWebAPIBuilder);

        public override void UseService(IApplicationServiceContext applicationServiceContext)
        {
            ICreateWebAPIBuilder createWebAPIBuilder = applicationServiceContext.GetRequiredService<ICreateWebAPIBuilder>();
            IEnumerable<IWebAPIMap> webAPIMaps = createWebAPIBuilder.GetWebAPIMaps();

            WebAPIBuilder webAPIBuilder;
            foreach (IWebAPIMap webAPIMap in webAPIMaps)
            {
                webAPIBuilder = new WebAPIBuilder(
                    webAPIMap.Group,
                    applicationServiceContext.GetEndpointRouteBuilder());

                webAPIMap.AddWebAPI(webAPIBuilder);
            }

            IApplicationBuilder applicationBuilder = applicationServiceContext.GetApplicationBuilder();
            _ = applicationBuilder.UseSwagger();
            _ = applicationBuilder.UseSwaggerUI(a =>
            {

                foreach (IWebAPIMap webAPIMap in webAPIMaps)
                {
                    a.SwaggerEndpoint($"/swagger/{webAPIMap.Group}/swagger.json", webAPIMap.Group);
                }
            });
        }
    }
}